<?php

namespace app\modules\admin\controllers;

use app\models\search\AuthItemSearch;
use Yii;
use app\models\Admin;
use app\models\search\AdminSearch;
use yii\rbac\Item;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\core\lib\AccessControl;
use yii\web\Response;

/**
 * AdminController implements the CRUD actions for Admin model.
 */
class AdminController extends AdminBaseController
{
    public $type = Item::TYPE_ROLE;

    /**
     * @inheritdoc
     */
//    public function behaviors()
//    {
//        return [
//            'verbs' => [
//                'class' => VerbFilter::className(),
//                'actions' => [
//                    'delete' => ['POST'],
//                ],
//            ],
//            'access' => [
//                'class' => AccessControl::className(),
//                'rules' => [
//                    [
//                        'actions' => ['index', 'view', 'create', 'update', 'delete', 'set-status', 'auth'],
//                        'allow' => true,
//                        'roles' => ['@'],
//                    ],
//                ],
//            ],
//        ];
//    }

//    public function init()
//    {
//        parent::init(); // TODO: Change the autogenerated stub
//        if (Yii::$app->user->identity->roles < 100) {
//            throw new BadRequestHttpException("對不起，您無權訪問此頁！");
//        }
//    }

    public function actionAuth($id) {
        $authManager = Yii::$app->authManager;
        $adminModel = $this->findModel($id);
        if(Yii::$app->request->isPost) {
            $roleName = Yii::$app->request->post('roleName', '');
            //删除用户所在的用户组
            $authManager->revokeAll($id);
            //添加用户组
            $authManager->assign($authManager->getRole($roleName), $id);
            $this->success('操作成功', $this->getForward(), true);
        }
        $searchModel = new AuthItemSearch();
        $searchModel->type = $this->type;
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        //获取当前用户的所有用户组
        $adminGroups = array_keys($authManager->getAssignments($id));
        //var_dump($dataProvider);exit();
        return $this->render('auth', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'adminGroups' => $adminGroups,
        ]);
    }

    /**
     * Lists all Admin models.
     * @return mixed
     */
    public function actionIndex()
    {
        $this->setForward();
        $searchModel = new AdminSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Admin model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Admin model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Admin();

        if ($model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                $this->success('操作成功', $this->getForward(), true);
            } else {
                $msg = '';
                foreach ($model->getFirstErrors() as $v) {
                $msg .= $v;
                }
                $this->error($msg,'#',true);
            }
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Admin model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
            if ($model->save()) {
                $this->success('操作成功', $this->getForward(), true);
            } else {
                $msg = '';
                foreach ($model->getFirstErrors() as $v) {
                    $msg .= $v;
                }
                $this->error('操作错误'.$msg,'#', true);
            }
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    public function actionSetStatus(){
        $id = Yii::$app->request->post('id', 0);
        $status = Yii::$app->request->post('status', 0);
        Yii::$app->response->format = Response::FORMAT_JSON;
        $admin = Admin::find()->where(['id'=>$id])->one();
        $admin->status = $status;
        $state=0;
        if ($admin->save()) {
            $state=1;
        }
        return [
            'state' => $state
        ];
    }

    /**
     * Deletes an existing Admin model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @return mixed
     */
    public function actionDelete()
    {
        $model = $this->findModel(0);
        if($this->delRow($model, 'id')) {
            $this->success('删除成功', $this->getForward(), true);
        } else {
            $this->error('删除失败！','#', true);
        }
    }

    /**
     * Finds the Admin model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Admin the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if($id == 0) {
            return new Admin();
        }
        if (($model = Admin::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
